<template>
  <div class="container">
    <el-dialog
      :title="showTitle"
      :visible="showDialog"
      width="30%"
      @close="handleClose"

    >
      <!-- form 表单 -->
      <el-form :model="Form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="活动名称" prop="subjectName">
          <el-input v-model="Form.subjectName"></el-input>
        </el-form-item>

        <el-form-item label="是否显示" prop="isFrontDisplay">
          <el-switch
            v-model="Form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submiting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects'
export default {
  name: 'subjectAdd',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    data: {
      default: () => {},
      type: Object
    }

  },
  computed: {
    showTitle () {
      return this.Form.id ? '编辑学科' : '新增学科'
    }
  },
  data () {
    return {
      submiting: false,
      Form: {
        id: null,
        subjectName: null,
        isFrontDisplay: true

      },
      rules: {
        subjectName: [
          {
            required: true,
            message: '请输入学科名称',
            trigger: ['blur', 'change']
          }
        ]

      }
    }
  },
  methods: {
    open () {
      this.show = true
      if (this.data.id) {
        const { id, subjectName, isFrontDisplay } = this.data
        this.Form = { id, subjectName, isFrontDisplay }
      } else {
        this.Form = {
          id: null,
          subjectName: null,
          isFrontDisplay: 1
        }
      }
      // 清除校验效果
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 关闭弹框
    handleClose () {
      this.$emit('update:showDialog', false)
      this.Form = {
        id: null,
        subjectName: null,
        isFrontDisplay: 1
      }
    },
    // 发起请求 添加 修改学科
    async handleSubmit () {
      await this.$refs.form.validate()
      // id存在就是修改
      if (this.data.id) {
        await update(this.Form)
        this.$message.success('学科修改成功')
      } else {
        this.submiting = true
        await add(this.Form)
        this.$message.success('学科添加成功')
        // this.$emit('addSubject')
      }
      // 子传父 渲染添加的数据到页面上
      this.$emit('addSubject')
      this.submiting = false
      this.handleClose()
    }
  }
}
</script>

<style scoped lang="less"></style>
